/**
 * Multicast project Bidois Morgan & Thomas Nunes
 *
 */
package middleware;

import Engine.Message;
import java.util.ArrayList;

/**
 * Data store of Messages
 *
 * @author thomas
 */
public class DataMulticast {

    private Message message;
    private boolean deliver = false;
    private ArrayList<Integer> listClientWhoAckThis = new ArrayList<>();
    private int numberOfAckWaited;

    public DataMulticast(Message mes, int nbClient) {
        this.message = mes;
        this.numberOfAckWaited = nbClient;
    }

    public DataMulticast(Message mes, boolean deliv, int nbClient) {
        this.message = mes;
        this.deliver = deliv;
        this.numberOfAckWaited = nbClient;
    }

    /**
     * Add the id of a client who ACK this message
     *
     * @param idCl
     * @return if it's possible to deliver this message.
     */
    public boolean addClientWhoAckThis(int idCl) {
        if (!this.listClientWhoAckThis.contains(idCl)) {
            this.listClientWhoAckThis.add(idCl);
        }
        return this.isPossible2Deliver();
    }

    public void setNumberOfAckWaited(int numberOfAckWaited) {
        this.numberOfAckWaited = numberOfAckWaited;
    }

    public boolean isPossible2Deliver() {
        return listClientWhoAckThis.size() >= numberOfAckWaited;
    }

    public int getLC() {
        return this.message.getLogicalClock();
    }

    public int getIdClient() {
        return this.message.getIdClient();
    }

    public Message getMessage() {
        return message;
    }

    public void setMessage(Message message) {
        this.message = message;
    }

    public boolean isDeliver() {
        return deliver;
    }

    public void setDeliver(boolean deliver) {
        this.deliver = deliver;
    }

    /**
     * notify that a client is dead. we stop to wait he's ACK.
     *
     * @param idCl
     * @return
     */
    public boolean thisClientIsAFK(int idCl) {
        if (this.listClientWhoAckThis.contains(idCl)) {
            return false;
            //This client have already ACK the message
        } else {
            //else, we stop to wait he's ACK
            this.numberOfAckWaited--;
        }
        return this.isPossible2Deliver();
    }

    @Override
    public String toString() {
        return "\n-deliver: " + this.deliver + " cl: " + this.getLC() + " id: " + this.getIdClient()
                + "  nbACK: " + listClientWhoAckThis.size() + " on " + this.numberOfAckWaited;
    }
}
